package cn.fatgod.learn.thymeleaf.format;

import cn.hutool.core.util.StrUtil;
import com.google.googlejavaformat.java.Formatter;
import com.google.googlejavaformat.java.FormatterException;

public class CodeFormat {

    /**
     * 格式化器
     */
    public final static Formatter FORMATTER = new Formatter();

    /**
     * 美化代码
     * @param sourceCode 源代码
     * @return 美化后代码
     */
    public static String pretty(String sourceCode) {
        try {
            return FORMATTER.formatSource(sourceCode);
        } catch (FormatterException e) {
            throw new RuntimeException(StrUtil.format("美化源代码错误，源代码为{}", sourceCode), e);
        }
    }

    private final static String LINE_SEPARATOR = System.lineSeparator();
    private final static String EMPTY = "";

    public static String format(String code) {
        return cleanExtLines(cleanUselessSpaces(code));
    }

    public static String cleanUselessSpaces(String str) {

        if (StrUtil.isBlank(str)) {
            return EMPTY;
        }
        StringBuilder builder = new StringBuilder();
        String[] lines = str.split(LINE_SEPARATOR);
        for (String line : lines) {
            builder.append(line.trim().equals(EMPTY) ? EMPTY : line)
                    .append(LINE_SEPARATOR);
        }
        return builder.toString();
    }

    public static String cleanExtLines(String str) {
        if (StrUtil.isBlank(str)) {
            return EMPTY;
        }
        String regex = LINE_SEPARATOR + "{3,}";
        return str.replaceAll(regex, StrUtil.repeat(LINE_SEPARATOR, 2));
    }
}
